package com.hibernate.hrm.dao;

import com.hibernate.hrm.entity.Department;
import com.hibernate.hrm.entity.Position;
import com.hibernate.hrm.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

public interface UserRepository extends JpaRepository<User, Integer>, JpaSpecificationExecutor<User> {

    // 根据用户名查询用户（带角色信息）
    @Query("SELECT u FROM User u LEFT JOIN FETCH u.roleId WHERE u.username = :username")
    Optional<User> findByUsername(@Param("username") String username);

    // 根据部门分页查询员工
    @Query("SELECT u FROM User u WHERE u.departmentID = :department AND u.status = true")
    Page<User> findByDepartmentID(@Param("department") Department department, Pageable pageable);

    // 查询所有在职员工（分页）
    @Query("SELECT u FROM User u WHERE u.status = true")
    Page<User> findAllActiveEmployees(Pageable pageable);

    long countByStartingDate(LocalDate startingDate);

    @Query("SELECT COUNT(u) FROM User u WHERE u.departmentID = :department AND u.status = :status")
    long countByDepartmentIDAndStatus(Department department, boolean status);

    @Query("SELECT u FROM User u WHERE u.departmentID = :department AND u.status = true")
    List<User> findByDepartmentIDAndStatusTrue(@Param("department") Department department);

    List<User> findByRoleId_RoleCodeInAndStatusTrue(List<String> roleCodes);
    long countByJobPositionID(Position position);
}